import { AnyAction } from "redux";
import { push } from "connected-react-router";
import * as TYPES from "../actiontypes";
import { APIvalidate, APIregister, APIlogin } from "@/api/profile";
import { message } from "bigbear-ui";
import { StoreDispatch } from "@/store/store";

export interface RegisterPayload {
	username: string;
	password: string;
	email: string;
	confirmPassword: string;
}
export interface RegisterResult {
	data: { token: string };
	success: boolean;
	message?: any;
}
export interface LoginPayload {
	username: string;
	password: string;
}
export interface LoginResult {
	data: { token: string };
	success: boolean;
	message?: any;
}

export default {
	validate(): AnyAction {
		return {
			type: TYPES.VALIDATE,
			payload: APIvalidate(),
		};
	},
	register(values: RegisterPayload) {
		return function (dispatch: StoreDispatch) {
			(async function () {
				try {
					let result: RegisterResult = await APIregister(values);
					if (result.success) {
						message.success("注册成功", {});
						dispatch(push("/login"));
					} else {
						message.danger(result.message, {});
					}
				} catch (error) {
					message.danger("注册失败", {});
				}
			})();
		};
	},
	login(values: LoginPayload) {
		return function (dispatch: StoreDispatch) {
			(async function () {
				try {
					let result: LoginResult = await APIlogin(values);
					if (result.success) {
						sessionStorage.setItem("access_token", result.data.token);
						dispatch(push("/profile"));
					} else {
						message.danger(result.message, {});
					}
				} catch (error) {
					message.danger("登录失败", {});
				}
			})();
		};
	},
	logout() {
		return function (dispatch: StoreDispatch) {
			sessionStorage.removeItem("access_token");
			dispatch({ type: TYPES.LOGOUT });
			dispatch(push("/login"));
		};
	},
	changeAvatar(avatar: string) {
		return {
			type: TYPES.CHANGE_AVATAR,
			payload: avatar,
		};
	},
};
